/*
 * @Description: 系统账户数据
 * @Author: xinqiao lxq1990.0716@qq.com
 * @Date: 2024-09-25
 * @LastEditors: xinqiao lxq1990.0716@qq.com
 * @LastEditTime: 2025-03-11
 */
import { requestGetUserCompanyList } from '/@/api/business/company'
import { requestSwitch } from '/@/api/system/ysys-user/company'
import { getCompanyInfo, saveCompanyInfo, saveCompanyList, saveModuleList as saveModuleListStore } from '/@/storage'

import { requestModuleList } from '../api/system/ysys-user/permission'

/**
 * 保存机构列表，并切换第一个机构
 */
export const saveCompanyListAndSwitch = async () => {
  const { responseData } = await requestGetUserCompanyList({})
  saveCompanyList(responseData)
  if (responseData?.length > 0) {
    await switchCompany(responseData[0].companyId, responseData[0].companyName)
  }
}

/**
 * 切换至当前机构
 * @param firstCompanyId 第1个机构id
 * @param fisrtCompanyName 第1个机构名称
 */
const switchCompany = async (firstCompanyId: number, firstCompanyName: string) => {
  let { companyId, companyName } = getCompanyInfo()
  // 未选中机构，缓存第一个机构作为当前机构
  if (!companyId) {
    companyId = firstCompanyId
    companyName = firstCompanyName
    saveCompanyInfo({ companyId, companyName })
  }
  const { responseCode } = await requestSwitch({ companyId, companyName })
  //if (responseCode === HttpCodeEnum.SUCCESS) await requestPlatformCompanyInit({})
}

/**
 * 保存模块列表
 */
export const saveModuleList = async () => {
  const { responseData } = await requestModuleList({})
  saveModuleListStore(responseData)
}
